require "proto/formation/message/ReqFormationsListMessage"
require "proto/formation/message/ReqSetFormationsMessage"
require "proto/formation/message/ReqFormationChangeNameMessage"
require "proto/formation/message/ReqFormationSortMessage"
require "proto/formation/message/ReqFormationDelMessage"
require "Common/define"
require "Logic/Config"
require "Common/functions"

---@class FormationManager
FormationManager = {};
local this = FormationManager;
local tableFormation = {};
local tempDungeonFormation = nil;
local tempDungeonFormationMore = nil;
local correctLvTable = {};

function FormationManager.SetFormation(formationType, formation,correctLv)
    tableFormation[formationType] = formation
    correctLvTable[formationType] = correctLv;
    for k, v in pairs(formation) do
        if type(v) == "table" then
            for i = 1, #v do
                tableFormation[formationType][k][i] = tostring(v[i]);
            end
        else
            tableFormation[formationType][k] = tostring(v);
        end
    end
    if formationType == EnumConst.FormationType.ArenaDef 
        or formationType == EnumConst.FormationType.FriendDefend 
        or formationType == EnumConst.FormationType.PlunderBattle
        or formationType == EnumConst.FormationType.CrossArenaDef
        or formationType == EnumConst.FormationType.TeamCrossArenaDef then
        --如果是防守阵容 更新防守红点
        FireEvent(Config.EventType.refreshDefFormation);
    end  
end
--检查防守阵容是否需要显示红点
function FormationManager.checkDefFormationRedDotByType( _type )
    if _type == EnumConst.FormationType.ArenaDef 
        or _type == EnumConst.FormationType.CrossArenaDef 
        or _type == EnumConst.FormationType.FriendDefend 
        or _type == EnumConst.FormationType.PlunderBattle then
        local formation = this.GetFormation( _type )
        if formation then
            for k, v in pairs(formation) do
                local level = logicMgr.HeroManager.getHeroShowLevelByPartnerId(v);
                if tonumber(level) == 1 then
                    return true
                end
            end
        end
    elseif _type == EnumConst.FormationType.TeamCrossArenaDef then
        local formation = this.GetFormation( _type )
        if formation then
            for _, v in pairs(formation) do
                if v ~= nil then
                    for _, v1 in pairs(v) do 
                        local level = logicMgr.HeroManager.getHeroShowLevelByPartnerId(v1)
                        if tonumber(level) == 1 then
                            return true
                        end
                    end
                end
            end
        end
    end
    return false
end

--- 新需求by斌立： 关卡阵容默认是空，通过引导进行第一次初始化
--- 战斗背景判断如果上阵列表是空，就默认上阵系统送的英雄
function FormationManager.GetFormation(formationType, useEmptryLogic)
    local heroTeamList = nil
    local preFormationType = formationType;
    if formationType == EnumConst.FormationType.DungeonEventPK and tableFormation[formationType] == nil then
        -- 主线随机pk临时用下主线阵容
        formationType = EnumConst.FormationType.Duplicate;
    end
    if tableFormation[formationType] ~= nil then
        --if preFormationType == EnumConst.FormationType.DungeonEventPK then
        --    heroTeamList = tableFormation[formationType];
        --elseif formationType == EnumConst.FormationType.Duplicate then
        --    if tempDungeonFormation ~= nil and logicMgr.DungeonRandomEventManager.getLeaseHero() ~= nil then
        --        heroTeamList = tempDungeonFormation;
        --    else
        --        heroTeamList = tableFormation[formationType];
        --    end
        --elseif formationType == EnumConst.FormationType.DuplicateMore then
        --    if tempDungeonFormationMore ~= nil and logicMgr.DungeonRandomEventManager.getLeaseHero() ~= nil then
        --        heroTeamList = tempDungeonFormationMore;
        --    else
        --        heroTeamList = tableFormation[formationType];
        --    end
        --else
            heroTeamList = tableFormation[formationType];
        --end
        local HasMan = false
        if type(heroTeamList[1]) == "table" then
            for k, v in pairs(heroTeamList) do
                for i = 1, EnumConst.TEAM_MAX_NUM do
                    if v[i] == nil or v[i] == 0 then
                        v[i] = 0;
                    else
                        HasMan = true
                    end
                end
            end
        else
            for i = 1, EnumConst.TEAM_MAX_NUM do
                if heroTeamList[i] == nil or heroTeamList[i] == 0 then
                    heroTeamList[i] = 0;
                else
                    HasMan = true
                end
            end
        end
        if useEmptryLogic and formationType == EnumConst.FormationType.Duplicate and HasMan == false then
            heroTeamList = {}
            local initHeroList = logicMgr.HeroManager.GetHeroListForBorn()
            for i = 1, EnumConst.TEAM_MAX_NUM do
                local heroInfo = initHeroList[i]
                if heroInfo then
                    heroTeamList[i] = tostring(heroInfo["partnerId"])
                else
                    heroTeamList[i] = "0"
                end
            end
        end
        return clone(heroTeamList)
    end
    return nil;
end

-- 临时维护下主线单队阵容
function FormationManager.TempDungeonFormation(formation)
    tempDungeonFormation = formation;
end
-- 临时维护下主线多队阵容
function FormationManager.TempDungeonFormationMore(formation)
    tempDungeonFormationMore = formation;
end

function FormationManager.OnDestroy()
    tableFormation = {}
    tempDungeonFormation = nil;
    tempDungeonFormationMore = nil;
end

----------------------------------------------阵容编辑 start 
this.teamList = {}
this.supSkill = {}
this.PetSkill = {}

local m_pre_remove = false

--存放队伍临时支援技
function FormationManager.SetTempSupskill(index, skill)
    this.supSkill[index] = skill
end

function FormationManager.ClearSupskill()
    this.supSkill = {}
end

function FormationManager.SetTempPetskill(index, skill)
    this.PetSkill[index] = skill
end

function FormationManager.ClearPetskill()
    this.PetSkill = {}
end

function FormationManager.GetTempPetskill(index)
    if this.PetSkill[index] then
        return this.PetSkill[index]
    end
    return 0
end

function FormationManager.GetTempSupskill(index)
    if this.supSkill[index] then
        return this.supSkill[index]
    end
    return 0
end

--获取编队
function FormationManager.GetEditorTeam(index, c)
    if this.teamList[index] then
        if c then
            return clone(this.teamList[index])
        end
        return this.teamList[index]
    end
    return nil
end

--当前显示上限
function FormationManager.GetMax()
    if this.defaultMax == nil then
        this.defaultMax = GetGlobalIntValue(561)
    end

    if this.formatMax == nil then
        this.formatMax =  GetGlobalIntValue(562)
    end

    if FormationManager.teamList then
        local count = table.getn(FormationManager.teamList)

        if count + 1 < this.defaultMax then
            return this.defaultMax
        else
            if count + 1 < this.formatMax then
                return count + 2
            else
                return this.formatMax
            end
        end
    else
        return this.defaultMax
    end
end

function FormationManager.GetFormationMaxConfig()
    if this.formatMax == nil then
        this.formatMax =  GetGlobalIntValue(562)
    end
    return this.formatMax
end

-- local isOpen = false
function FormationManager.IsOpen()
    return logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.TeamEditor)
end

--请求列表
function FormationManager.req_FormationList()
    local req = ReqFormationsListMessage.New()
    sendReqMessage(req)
end

function FormationManager.res_FormationList(msg)
    FormationManager.teamList = {}
    local tb
    FormationManager.ClearSupskill()
    FormationManager.ClearPetskill()
    for k,v in pairs(msg.formations) do
        tb = {skill = tonumber(tostring(v.supportSkill)), team = {}, index = k,petSkill =tonumber(tostring(v.petSkillId)) }
        tb.name = v.name or (getLanguage("UIBattleManyTeams1001") .. k)
        for i=1, #v.formation do
            tb.team[i] = tostring(v.formation[i])
        end
        table.insert(FormationManager.teamList, tb)
        FormationManager.SetTempSupskill(tb.index, tb.skill)
        FormationManager.SetTempPetskill(tb.index,tb.petSkill)
    end
    FireEvent(Config.EventType.RefreshFormationList)

    if m_pre_remove then
        UISysTips.AddMsg(getLanguage("UIBattleManyTeams1012"))
        m_pre_remove = false
    end
end

--设置编队
function FormationManager.req_SetFormation(id, formation, name)
    local same = false
    local same_index = 0
    local sp = FormationManager.GetTempSupskill(id)

    FormationManager.SetFocus(id)

    for i=1, #formation do
        if formation[i] == 0 then
            formation[i] = "0"
        end
    end

    same,same_index = FormationManager.CompareAll(formation, sp)
    if same then
        if same_index == id then

        else
            UISysTips.AddMsg(getLanguage("UIBattleManyTeams1009"))
        end
    else
        local req = ReqSetFormationsMessage.New()
        req.index = id
        req.formation = formation
        req.supportSkill = FormationManager.GetTempSupskill(id)
        req.petSkillId = FormationManager.GetTempPetskill(id)
        if name then
            req.name = name
        else
            local t = FormationManager.GetEditorTeam(id)
            if t then
                req.name = t.name
            else
                req.name = getLanguage("UIBattleManyTeams1001").. id
            end
        end

        sendReqMessage(req)
    end
end

function FormationManager.res_SetFormations(msg)
    local tm = msg.formation
    local sp = tostring(msg.supportSkill)
    local ps = tostring(msg.petSkillId)

    local tb = {skill = tonumber(sp), team = {}, index = msg.index,petSkill =tonumber(ps) }
    tb.name = msg.name or (getLanguage("UIBattleManyTeams1001") .. msg.index)

    for k,v in pairs(tm) do
        tb.team[k] = tostring(v)
    end
    FormationManager.SetTempSupskill(msg.index, tb.skill)
    FormationManager.SetTempPetskill(msg.index,tb.petSkill)
    FormationManager.teamList[msg.index] = tb

    FireEvent(Config.EventType.FormationSetFinish)
end

--编队改名
function FormationManager.req_RenameFormation(id, name)
    local req =  ReqFormationChangeNameMessage.New()
    req.index = id
    req.name = name
    sendReqMessage(req)
end

function FormationManager.res_FormationChangeName(msg)
    local t = FormationManager.teamList[msg.index]
    t.name = msg.name
    FireEvent(Config.EventType.RefreshFormationList)
end

--置顶
function FormationManager.req_FormationSort(index)
    if FormationManager.teamList[index] then
        local req =  ReqFormationSortMessage.New()
        req.index = index
        sendReqMessage(req)
    else

    end
end

--删除
function FormationManager.req_FormationRemove(index)
    if FormationManager.teamList[index] then
        m_pre_remove = true
        local req =  ReqFormationDelMessage.New()
        req.index = index
        sendReqMessage(req)
    else

    end
end

local select_index
function FormationManager.SetFocus(index)
    --logError("焦点：" .. index)
    select_index = index
end

function FormationManager.GetFocus()
    return select_index
end


function FormationManager.GetAllFormation()
    return FormationManager.teamList
end

function FormationManager.IsInEditor()
    if isOpenUI(PanelResNames.UIBattleManyTeams) then
        return true
    end
    return false
end

--检测是否有相同阵容
function FormationManager.CompareAll(formation, sp)
    for k,v in pairs(FormationManager.teamList) do
        if sp == v.skill and CompareTable(v.team, formation) then
            return true,v.index
        end
    end
    return false
end

function FormationManager.GetCorrectLv(formationType)
    return correctLvTable[formationType] or 0;
end
----------------------------------------------阵容编辑 end 

return FormationManager